const path=require('path');
const utils=require('../modules/utils');

(async ()=>{
    let txt=await utils.readFile(path.join(__dirname,'downloadImgRets.json'),'utf8');
    if(!txt)return console.error('readFile',err);

    let data;
    try{
        data=JSON.parse(txt);
    }catch(err){
        return console.error('parse',err);
    }


    let rets=data.map(list=>utils.flatten(list));

    //过滤抓取错误的图片
    rets=rets.map(list=>{
        return list.filter(item=>!item.error);
    });

    //console.log(rets);

    // utils.writeFile(path.join(__dirname,'rets.json'),JSON.stringify(rets,null,2));

    let [books,comments]=[[...rets[0],...rets[1]],[...rets[2],...rets[3]]];

    //await utils.writeFile(path.join(__dirname,'books.json'),JSON.stringify(books,null,2));
    //await utils.writeFile(path.join(__dirname,'comments.json'),JSON.stringify(comments,null,2));


    let bookUpdates=[];
    for(let item of books){
        let sku=item.data.sku,field=item.data.field,fileName=item.fileName;
        let book=bookUpdates.find(item=>item.sku==sku&&item.field==field);
        if(book){
            book.data.push(fileName);
        }else{
            bookUpdates.push({
                sku,
                field,
                data:[fileName]
            });
        }
    }
    await utils.writeFile(path.join(__dirname,'bookUpdates.json'),JSON.stringify(bookUpdates,null,2));



    //console.log(bookUpdates);
    //console.log(bookSkus);

    let commentUpdates=[];
    for(let item of comments){
        let sku=item.data.sku,idx=item.data.idx;
        let field='76x76'==item.data.size?'smalls':'bigs',fileName=item.fileName;

        let comment=commentUpdates.find(item=>item.sku==sku&&item.idx==idx&&field==item.field);
        if(comment){
            comment.data.push(fileName);
        }else{
            commentUpdates.push({
                sku,
                idx,
                field,
                data:[fileName]
            });
        }
    }
    await utils.writeFile(path.join(__dirname,'commentUpdates.json'),JSON.stringify(commentUpdates,null,2));







})();
